﻿CREATE PROCEDURE [ServiceEngine].[ListRuntimeEventDataForPolicyID]
	@PolicyID uniqueidentifier 
AS
BEGIN
	
--policy for operations resources, system, system instance
	SELECT DISTINCT rse.RuntimeServerID, rse.EndpointID, ov.OperationID
	FROM ServiceEngine.OperationVersions ov
		INNER JOIN ServiceEngine.Endpoints_AssociatedOperations eao ON eao.OperationVersionID = ov.OperationVersionID
		INNER JOIN ServiceEngine.RuntimeServers_Endpoints rse ON eao.EndpointID = rse.EndpointID
		INNER JOIN ServiceEngine.Operations o ON o.OperationID = ov.OperationID
		INNER JOIN ServiceEngine.Resources r ON r.ResourceID = ov.ResourceID
		INNER JOIN ServiceEngine.SystemInstances si ON r.InstanceID = si.InstanceID
		INNER JOIN ServiceEngine.Systems s ON s.SystemID = si.SystemID
	WHERE o.PolicyID = @PolicyID OR ov.PolicyID = @PolicyID
		OR r.PolicyID = @PolicyID OR s.PolicyID = @PolicyID OR si.PolicyID = @PolicyID 
	UNION
	SELECT DISTINCT rse.RuntimeServerID, rse.EndpointID, ov.OperationID
	FROM ServiceEngine.OperationVersions ov
		INNER JOIN ServiceEngine.Endpoints_PublishedOperations epo ON epo.OperationVersionID = ov.OperationVersionID
		INNER JOIN ServiceEngine.RuntimeServers_Endpoints rse ON epo.EndpointID = rse.EndpointID
		INNER JOIN ServiceEngine.Operations o ON o.OperationID = ov.OperationID
		INNER JOIN ServiceEngine.Resources r ON r.ResourceID = ov.ResourceID
		INNER JOIN ServiceEngine.SystemInstances si ON r.InstanceID = si.InstanceID
		INNER JOIN ServiceEngine.Systems s ON s.SystemID = si.SystemID
	WHERE o.PolicyID = @PolicyID OR ov.PolicyID = @PolicyID
		OR r.PolicyID = @PolicyID OR s.PolicyID = @PolicyID OR si.PolicyID = @PolicyID 
	UNION
--policy for endpoints
	SELECT DISTINCT rse.RuntimeServerID, rse.EndpointID, null
	FROM ServiceEngine.RuntimeServers_Endpoints rse 
		INNER JOIN ServiceEngine.EndPoints e ON e.EndPointID = rse.EndpointID
	WHERE e.PolicyID = @PolicyID
	UNION
--policy for runtime servers
	SELECT DISTINCT rs.RuntimeServerID, null, null
	FROM ServiceEngine.RuntimeServers rs
	WHERE rs.PolicyID = @PolicyID

END